package mapkit.carto
{
	import flash.geom.Point;

	public class MapLocator implements IMapLocator
	{
		public static const EPSG4326:String="EPSG:4326";

		final public function toMapPoint(pt_:Point, map:IMap):Location
		{
			var x:Number;
			var y:Number;
			switch (map.extent.srid.toUpperCase())
			{
				case "":
				case "EPSG:4326":
					x=pt_.x / map.width * map.extent.width + map.extent.minX;
					y=map.extent.maxY - pt_.y / map.height * map.extent.height;
					break;
				default:
					throw ReferenceError("MapLocator.toMapPoint NOT Support SRS<" +
						map.extent.srid + ">");
					break;
			}
			return new Location(x, y);
		}

		final public function fromMapPoint(pt_:Location, map:IMap):Point
		{
			var x:Number;
			var y:Number;
			switch (map.extent.srid)
			{
				case "":
				case "EPSG:4326":
					x=map.width / map.extent.width * (pt_.x - map.extent.minX);
					y=map.height / map.extent.height * (map.extent.maxY - pt_.y);
					break;
				default:
					throw ReferenceError("MapLocator.fromMapPoint NOT Support SRS<" +
						map.extent.srid + ">");
					break;
			}

			return new Point(x, y);
		}

		final public function project(loc1:Location, srid2:String):Location
		{
			var x:Number;
			var y:Number;
			switch (loc1.srid)
			{
				case "":
				case "EPSG:4326":
					switch (srid2)
				{
					case "EPSG:900913":
						x=loc1.x;
						y=Math.log(Math.tan(0.25 * Math.PI + 0.5 * loc1.y));
						break;
				}
					break;
				case "EPSG:900913":
					switch (srid2)
				{
					case "":
					case "EPSG:4326":
						x=loc1.x;
						y=2 * Math.atan(Math.pow(Math.E, loc1.y)) - 0.5 * Math.PI;
						break;
				}
					break;
			}
			if (x is undefined || y is undefined)
			{
				throw ReferenceError("MapLocator.project NOT Support transform from SRS<" +
					loc1.srid + "> to SRS<" + srid2 + ">");
			}
			return new Location(x, y, srid2);
		}

	}
}
